package com.ashin.handler;

import com.ashin.config.QqConfig;
import com.ashin.entity.bo.ChatBO;
import com.ashin.exception.ChatException;
import com.ashin.service.InteractService;
import com.ashin.util.BotUtil;
import com.ashin.util.FileUtils;
import com.ashin.util.QQUtils;
import net.mamoe.mirai.contact.Friend;
import net.mamoe.mirai.contact.Group;
import net.mamoe.mirai.contact.MessageTooLargeException;
import net.mamoe.mirai.event.EventHandler;
import net.mamoe.mirai.event.ListenerHost;
import net.mamoe.mirai.event.events.*;
import net.mamoe.mirai.message.data.*;
import net.mamoe.mirai.utils.ExternalResource;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

/**
 * QQ消息处理程序
 *
 * @author ashinnotfound
 * @date 2023/2/1
 */
@Component
public class QqMessageHandler implements ListenerHost {
    @Resource
    private InteractService interactService;
    @Resource
    private QqConfig qqConfig;
    @Resource
    private BotUtil botUtil;
    /**
     * 好友消息事件
     *
     * @param event 事件
     */
    @EventHandler
    public void onUserMessageEvent(UserMessageEvent event){
        ChatBO chatBO = new ChatBO();
        chatBO.setSessionId(String.valueOf(event.getSubject().getId()));
        System.out.println("---------onUserMessageEvent:"+chatBO.getSessionId());
    }
    /**
     * 好友消息事件
     *
     * @param event 事件
     */
    @EventHandler
    public void onFriendMessageEvent(FriendMessageEvent event){
        ChatBO chatBO = new ChatBO();
        chatBO.setSessionId(String.valueOf(event.getSubject().getId()));
        String prompt = event.getMessage().contentToString().trim();
        response(event, chatBO, prompt);
        System.out.println("---------onFriendMessageEvent:"+chatBO.getSessionId());
    }

    /**
     * 群聊消息事件
     *
     * @param event 事件
     */
    @EventHandler
    public void onGroupMessageEvent(GroupMessageEvent event){
        ChatBO chatBO = new ChatBO();
        chatBO.setSessionId(String.valueOf(event.getSubject().getId()));
        String temp = event.getMessage().contentToString();
        if (event.getMessage().contains(new At(event.getBot().getId()))) {
            //存在@机器人的消息就向ChatGPT提问
            //去除@再提问
            String prompt = temp.replace("@" + event.getBot().getId(), "").trim();
            response(event, chatBO, prompt);
        }
        else if(temp.contains("#bot")){
            String prompt = temp.replace("#bot" , "").trim();
            response(event, chatBO, prompt);
        }
        System.out.println("---------onGroupMessageEvent:"+chatBO.getSessionId());
    }
    private void response(@NotNull MessageEvent event, ChatBO chatBO, String prompt) {
        if (qqConfig.getResetWord().equals(prompt)) {
            //检测到重置会话指令
            botUtil.resetPrompt(chatBO.getSessionId());
            event.getSubject().sendMessage("重置会话成功");
        }  else {
            String response="unknown error!";
            try {
                //在此对prompt进行分流
                //if(prompt.contains("#chatgpt"))
                    //response = interactService.chat(chatBO);
                //chatgpt
                if(prompt.contains("#gpt")){
                     if(prompt.contains("#gpt4")){
                         prompt= prompt.replace("#gpt","");
                         chatBO.setPrompt(prompt);
                         response = interactService.linkAiChat(chatBO,true);
                    }
                    else {
                         prompt= prompt.replace("#gpt","");
                         chatBO.setPrompt(prompt);
                         response = interactService.linkAiChat(chatBO,false);
                     }
                }
                //发送使用说明的图片
                else if (prompt.contains("#命令")||prompt.contains("#使用")||prompt.contains("#设置")) {
                   sendImg("data/usage.png",event);
                   return;
                }
                //sd
                else if(prompt.contains("#语音")) {
                    prompt=prompt.replace("#语音","");
                    String model = QQUtils.getVoiceModel(prompt);
                    prompt=prompt.replace("#model","");
                    prompt=prompt.replace(model+"#","");
                    chatBO.setPrompt(prompt);
                    File silk = interactService.audioChat(model,chatBO);
                    if(silk==null)
                        sendImg(QQUtils.usagePng,event);
                    else
                        sendVoice(silk,event);
                    return;
                }
                //转语音
                else if(prompt.contains("#转语音")) {
                    prompt=prompt.replace("#转语音","");
                    String model = QQUtils.getVoiceModel(prompt);
                    prompt=prompt.replace("#model","");
                    prompt=prompt.replace(model+"#","");

                    File silk = interactService.textToAudio(prompt,prompt);
                    if(silk==null)
                        sendImg(QQUtils.usagePng,event);
                    else{
                        sendVoice(silk,event);
                    }
                    return;
                }
                //唱歌
                else if(prompt.contains("#唱歌")) {
                    prompt=prompt.replace("#唱歌","");
                    chatBO.setPrompt(prompt);
                    response = interactService.qwenChat(chatBO);
                }
                //sd
                else if(prompt.contains("#图片")) {
                    prompt= prompt.replace("#图片","");
                    chatBO.setPrompt(prompt);
                    String imagePath = interactService.sdImageChat(chatBO,prompt);
                    sendImg(imagePath,event);
                    return;
                }
                //sd
                else if(prompt.contains("#每日亿图")) {
                    prompt= prompt.replace("#每日亿图","");
                    chatBO.setPrompt(prompt);
                    String imagePath = interactService.localImageChat(chatBO,prompt);
                    if(StringUtils.isNotBlank(imagePath))
                        sendImg(imagePath,event);
                    else sendImg(QQUtils.usagePng,event);
                    return;
                }
                //qianwen
                else {
                    prompt= prompt.replace("#qianwen","");
                    chatBO.setPrompt(prompt);
                    response = interactService.qwenChat(chatBO);
                }

            }catch (ChatException e){
                response = e.getMessage();
            }

            try {
                MessageChain messages = new MessageChainBuilder()
                        .append(new QuoteReply(event.getMessage()))
                        .append(response)
                        .build();
                event.getSubject().sendMessage(messages);
            }catch (MessageTooLargeException e){
                //信息太大，无法引用，采用直接回复
                event.getSubject().sendMessage(response);
            }
        }
    }

    /**
     * 好友申请事件
     *
     * @param event 事件
     */
    @EventHandler
    public void onNewFriendRequestEvent(NewFriendRequestEvent event){
        if (qqConfig.getAcceptNewFriend()){
            event.accept();
        }
    }

    /**
     * 群聊邀请事件
     *
     * @param event 事件
     */
    @EventHandler
    public void onNewGroupRequestEvent(BotInvitedJoinGroupRequestEvent event){
        if (qqConfig.getAcceptNewGroup()){
            event.accept();
        }
    }
    /**发送图片*/
    private void sendImg(String url,MessageEvent event){
        if(StringUtils.isBlank(url))return;
        ExternalResource ex = null;
        try {
            ex = ExternalResource.Companion.create(FileUtils.readImageToByteArray(url));
            Image img = ExternalResource.uploadAsImage(ex, event.getSubject());
            MessageChain chain = new MessageChainBuilder()
                    .append(img)
                    .build();
            event.getSubject().sendMessage(chain);
            ex.close();
        } catch (IOException e) {
        }
    }
    /**发送语音，url要为amr/silk*/
    private void sendVoice(String url,MessageEvent event){
        try {
            File voiceFile = new File(url);
            if (!voiceFile.exists()) {
                System.out.println("音频文件不存在");
                return;
            }
            if (event.getSubject() instanceof Group) {
                Group group = (Group) event.getSubject();
                ExternalResource resource = ExternalResource.create(voiceFile);
                OfflineAudio audio = group.uploadAudio(resource);
                group.sendMessage(audio);
                resource.close();
            }
            if (event.getSubject() instanceof Friend) {
                Friend user = (Friend) event.getSubject();
                ExternalResource resource = ExternalResource.create(voiceFile);
                OfflineAudio audio = user.uploadAudio(resource);
                user.sendMessage(audio);
                resource.close();
            }
        } catch (IOException e) {
        }
    }
    /**发送语音，url要为amr/silk*/
    private void sendVoice(File voiceFile,MessageEvent event){
        try {
            if (event.getSubject() instanceof Group) {
                Group group = (Group) event.getSubject();
                ExternalResource resource = ExternalResource.create(voiceFile);
                OfflineAudio audio = group.uploadAudio(resource);
                group.sendMessage(audio);
                resource.close();
            }
            if (event.getSubject() instanceof Friend) {
                Friend user = (Friend) event.getSubject();
                ExternalResource resource = ExternalResource.create(voiceFile);
                OfflineAudio audio = user.uploadAudio(resource);
                user.sendMessage(audio);
                resource.close();
            }
        } catch (IOException e) {
        }
    }


}